<template>
    <div class="user-resource">
        <div class="user-hared">
            <el-button type="primary" size="mini" @click="handleBtnAdd" v-authCode.show="B_0346">新增 </el-button>
            <el-button type="primary" size="mini" @click="openSelectUserInfo" v-authCode.show="B_0347">查询 </el-button>
            <el-button type="primary" size="mini" @click="openMenuSort" v-authCode.show="B_0148">菜单顺序 </el-button>
            <el-button type="primary" size="mini" @click="loadout" v-authCode.show="B_0348">导出JSON文件 </el-button>
        </div>
        <!-- 查询 -->
        <div>
            <yh-dialog
                drag
                title="查询菜单信息"
                :visible.sync="dialogVisible"
                width="500px"
                label-width="130px"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
            >
                <el-form ref="form" :model="selectInfo" label-width="120px" size="mini">
                    <el-form-item label="资源编码">
                        <el-input size="mini" v-model="selectInfo.resourceCode" class="dialog-p-input" />
                    </el-form-item>
                    <el-form-item label="资源名称">
                        <el-input size="mini" v-model="selectInfo.resourceName" class="dialog-p-input" />
                    </el-form-item>
                    <el-form-item label="资源类型">
                        <el-select v-model="selectInfo.sourceType" class="dialog-p-input" clearable>
                            <el-option v-for="item in menuData" :key="item.name" :label="item.name" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="父资源编码">
                        <el-input size="mini" v-model="selectInfo.resourceParentCode" class="dialog-p-input" />
                    </el-form-item>
                    <el-form-item label="是否使用">
                        <el-select v-model="selectInfo.show" class="dialog-p-input" clearable>
                            <el-option label="是" :value="true"> </el-option>
                            <el-option label="否" :value="false"> </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="dialogVisible = false"> 取 消 </el-button>
                    <el-button size="mini" @click="resetInfo">重置</el-button>
                    <el-button size="mini" type="primary" @click="selectUserInfo()">确 定 </el-button>
                </div>
            </yh-dialog>
        </div>
        <!-- 菜单顺序 -->
        <div>
            <yh-dialog
                drag
                title="菜单顺序设置:"
                :visible.sync="dialogMenu"
                width="500px"
                v-loading="loading"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
            >
                <div class="user-resource-div">
                    <div class="user-resource-div-lift">
                        <p>一级菜单设置</p>
                        <div class="user-resource-text-conter">
                            <VueDraggable
                                v-model="leftMeneData"
                                chosen-class="chosen"
                                force-fallback="true"
                                group="people1"
                                animation="1000"
                                @change="draggableChange"
                                :key="draggableKeyLeft"
                            >
                                <p v-for="item in leftMeneData" :key="item.key" @click="getMenuKey(item.key)">
                                    <span>{{ item.key }}</span>
                                    -
                                    <span>{{ item.resourceName }}</span>
                                </p>
                            </VueDraggable>
                        </div>
                    </div>
                    <div class="user-resource-div-right">
                        <p>二级菜单设置</p>
                        <div class="user-resource-text-conter">
                            <VueDraggable v-model="rightMeneData" chosen-class="chosen" force-fallback="true" group="people2" animation="1000">
                                <p v-for="rInfo in rightMeneData" :key="rInfo.key">
                                    <span>{{ rInfo.key }}</span>
                                    -
                                    <span>{{ rInfo.resourceName }}</span>
                                </p>
                            </VueDraggable>
                        </div>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="dialogMenu = false"> 取 消 </el-button>
                    <el-button size="mini" type="primary" @click="setupMenu">确 定 </el-button>
                </div>
            </yh-dialog>
        </div>
        <!-- 数据 -->
        <div class="resource-list">
            <!-- height="calc(100vh - 176px)" -->
            <el-table
                :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0', 'text-align': 'center' }"
                :cell-style="{ padding: '0' }"
                :row-style="{ height: '35px' }"
                :header-row-style="{ height: '35px', padding: '5px 0' }"
                ref="multipleTable"
                :data="tableData"
                style="width: 100%"
                border
                size="mini"
                v-loading="loading"
                v-tableTop="currentPage"
                :key="key + 'key'"
                :height="'calc(100vh - 176px)'"
            >
                <el-table-column prop="resourceCode" label="资源编码"> </el-table-column>
                <el-table-column prop="resourceParentCode" label="父资源编码"> </el-table-column>
                <el-table-column prop="resourceName" label="资源名称" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="sourceType" label="资源类型">
                    <template slot-scope="scope">
                        {{ scope.row.sourceType == '1' ? '菜单' : '按钮' }}
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序号"></el-table-column>
                <el-table-column prop="show" label="是否使用">
                    <template slot-scope="scope">
                        <span v-show="scope.row.show === true">是</span>
                        <span v-show="scope.row.show === false">否</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="90" fixed="right">
                    <template slot-scope="scope">
                        <el-tooltip placement="bottom">
                            <div slot="content">编辑</div>
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="lookeMuenInfo(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <risk-pagination :paging="pages" @page-change="handleCurrentChange"></risk-pagination>
            </div>
        </div>
        <!-- 新增、修改 -->
        <div>
            <yh-dialog
                drag
                :title="dialogAUTitle"
                :visible.sync="dialogAU"
                width="500px"
                v-loading="loading"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
            >
                <el-form ref="form" label-width="130px" :modal="menuInfo" size="mini">
                    <el-form-item label="资源编码">
                        <el-input size="mini" v-model="menuInfo.resourceCode" class="dialog-p-input" disabled />
                    </el-form-item>
                    <el-form-item label="资源名称">
                        <el-input size="mini" v-model="menuInfo.resourceName" class="dialog-p-input" />
                    </el-form-item>
                    <el-form-item label="资源类型">
                        <el-select v-model="menuInfo.sourceType" class="dialog-p-input" size="mini" @change="handleParams('sourceType')">
                            <el-option v-for="item in menuData" :key="item.name" :label="item.name" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="父资源编码">
                        <Treeselect
                            v-model="menuInfo.resourceParentCode"
                            placeholder="请选择"
                            :multiple="false"
                            :options="menuResources"
                            :disable-branch-nodes="menuInfo.sourceType == '2'"
                            noOptionsText="暂无数据"
                            noResultsText="无匹配数据"
                            :normalizer="normalizer"
                            @select="handleTreeSelect"
                            class="dialog-p-input"
                            :max-height="110"
                            size="mini"
                            :key="resourceKey"
                            :default-expand-level="1"
                            :ref="'tree-select'"
                        />

                        <!-- :default-expand-level="1" :append-to-body="true" :max-height="200" -->
                        <!-- <el-input size="mini" v-model="menuInfo.resourceParentCode" class="dialog-p-input" /> -->
                    </el-form-item>
                    <el-form-item label="菜单路径" v-if="menuInfo.sourceType == '1'">
                        <el-input size="mini" v-model="menuInfo.menuUrl" class="dialog-p-input" />
                    </el-form-item>
                    <el-form-item label="是否使用">
                        <el-switch size="mini" active-color="#13ce66" inactive-color="#eee" v-model="menuInfo.show"> </el-switch>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="dialogAU = false"> 取 消 </el-button>
                    <el-button size="mini" type="primary" @click="menuInfoConfirm"> 确 定 </el-button>
                </div>
            </yh-dialog>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { resourceList, menuData, manageData } from './tables';
import { getCurrentPageData, uniqueFunc } from '@/utils/tools';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { downLoadFile } from '@/utils/request';
import { getUser } from '@/utils/user-util';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'UserResource',
    components: {
        RiskPagination,
    },
})
export default class UserResource extends Vue {
    // 列表数据
    private tableData: any = [];
    key: number = -1; //
    // 这是接口返回的数据，不能动
    private tableDataInfo: any;
    // 过滤后的总数据
    private sumUserInfo: any;
    menuResources = [];
    pages: pages = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    resourceKey: number = 0;
    // resourceTreeData: any[] = [];

    private loading: boolean = false;
    private dialogVisible: boolean = false;
    private dialogMenu: boolean = false;
    private dialogAU: boolean = false;
    dialogAUTitle: string = '';
    dialogAUType: string = 'add';
    private superuser: boolean = false;
    draggableKeyLeft: number = -1;
    private rightMenuDataAll: any;
    private leftMeneData: any;
    private rightMeneData: menuData[] = [
        {
            createDate: 0,
            createTime: 0,
            key: '',
            menuIcon: '',
            menuUrl: '',
            parentValid: false,
            resourceCode: '',
            resourceName: '',
            resourceParentCode: '',
            show: false,
            sort: 0,
            sourceType: '',
        },
    ];
    private menuData: resourceList[] = [
        {
            id: '1',
            name: '菜单',
        },
        {
            id: '2',
            name: '按钮',
        },
    ];
    private menuInfo: menuData = {
        createDate: 0,
        createTime: 0,
        key: '',
        menuIcon: '',
        menuUrl: '',
        parentValid: false,
        resourceCode: '',
        resourceName: '',
        resourceParentCode: null,
        show: false,
        sort: 0,
        sourceType: '1',
    };

    private menuInfoModule: menuData = {
        createDate: 0,
        createTime: 0,
        key: '',
        menuIcon: '',
        menuUrl: '',
        parentValid: false,
        resourceCode: '',
        resourceName: '',
        resourceParentCode: null,
        show: false,
        sort: 0,
        sourceType: '1',
    };
    private selectInfo: manageData = {
        resourceCode: '',
        resourceName: '',
        resourceParentCode: '',
        sourceType: '',
        show: null,
    };
    private selectInfoBackup: manageData = {
        resourceCode: '',
        resourceName: '',
        resourceParentCode: '',
        sourceType: '',
        show: null,
    };

    normalizer(node) {
        if ((node.level == 3 && this.menuInfo.sourceType == '1') || node.resourceName == '首页') {
            // delete node.children;
            node['isDisabled'] = true;
        } else {
            node['isDisabled'] = false;
        }
        return {
            id: node.resourceCode,
            label: node.resourceName,
            children: node.children,
        };
    }

    mounted() {
        this.getUserResource();
        // this.getResourcceTree();
    }

    // 参数处理
    handleParams(type: string) {
        if (type == 'sourceType') {
            this.menuInfo.resourceParentCode = null;
            this.resourceKey++;
        }
    }

    // 获取树形结构菜单资源
    // private getResourcceTree() {
    //     this.$axios('/role/menu/queryAll').then((response: any) => {
    //         this.resourceTreeData = response || [];
    //     });
    // }

    // 选中事件
    handleTreeSelect(node) {
        console.log(node);
        this.menuInfo.resourceParentCode = node.resourceParentCode;
        console.log(this.menuInfo.resourceParentCode, 'menuInfo.resourceParentCode');
        this.menuInfo['level'] = node.level || 0;
        console.log(this.menuInfo['level'], '------------------');
    }

    // 列表组装成树形集合
    private createTreeList(orginalList, startCode, level: number): any {
        let newList = [];

        for (let i = 0; i < orginalList.length; i++) {
            if (orginalList[i].resourceParentCode === startCode) {
                orginalList[i].level = level;
                if (orginalList.find(item => item.resourceParentCode === orginalList[i].resourceCode)) {
                    orginalList[i].children = this.createTreeList(orginalList, orginalList[i].resourceCode, level + 1);
                }
                newList.push(orginalList[i]);
            }
        }
        return newList;
    }

    // 获取数据
    private getUserResource(isFilter: boolean = false): void {
        this.loading = true;
        this.$axios
            .get('/userManage/resource/all')
            .then((res: any) => {
                this.loading = false;
                if (res) {
                    res.sort((a: any, b: any) => {
                        let bm = (a.resourceCode.includes('M') ? 0 : 1) - (b.resourceCode.includes('M') ? 0 : 1);
                        if (bm === 0) {
                            return a.resourceCode.replace(/[^0-9]/gi, '') - b.resourceCode.replace(/[^0-9]/gi, '');
                        } else {
                            return bm;
                        }
                    });
                    res.forEach((item: any) => (item.key = item.resourceCode));
                    if (getUser().resources) {
                        const resources = getUser().resources;
                        this.tableData = getCurrentPageData(resources, this.pages.currentPage, this.pages.pageSize);
                        this.pages.total = resources.length;
                    }
                    this.tableDataInfo = res;
                    this.leftMeneData = this.tableDataInfo.filter((item: any) => item.sourceType === '1' && item.parentValid);
                    this.sumUserInfo = this.tableDataInfo;

                    isFilter && this.selectUserInfo(this.pages.currentPage, false);
                    let data1 = res.filter(item => item.sourceType == '1');
                    this.menuResources = [{ resourceCode: '0', resourceName: '系统', children: this.createTreeList(data1, '0', 1) }];
                    console.log(data1, this.menuResources, 'menuResources');
                }
            })
            .catch(() => {
                this.loading = false;
            });
    }

    private openSelectUserInfo() {
        this.dialogVisible = true;
        this.selectInfo = { ...this.selectInfoBackup };
    }

    // 打开菜单顺序
    openMenuSort() {
        this.dialogMenu = true;
        this.rightMeneData = [];
        this.rightMenuDataAll = JSON.parse(JSON.stringify(this.tableDataInfo));
    }

    // 查询
    private selectUserInfo(curPage: number = 1, showMessage: boolean = true): void {
        // 查询的时候页数归1
        this.pages.currentPage = curPage;
        this.selectInfoBackup = { ...this.selectInfo };
        this.sumUserInfo = this.handleFilter(this.tableDataInfo, this.selectInfo);
        this.pages.total = this.sumUserInfo.length;
        this.tableData = getCurrentPageData(this.sumUserInfo, this.pages.currentPage, this.pages.pageSize);
        this.dialogVisible = false;
        showMessage && this.yh_message_success('查询成功');
    }

    // 过滤数据
    private handleFilter(dataSource: any, param: any): any {
        return dataSource.filter((item: any) => {
            return (
                (!param.resourceCode || item.resourceCode.includes(param.resourceCode)) &&
                (!param.resourceName || item.resourceName.includes(param.resourceName)) &&
                (!param.resourceParentCode || item.resourceParentCode.includes(param.resourceParentCode)) &&
                (!param.sourceType || item.sourceType === param.sourceType) &&
                (typeof param.show !== 'boolean' || item.show === param.show)
            );
        });
    }

    // 菜单设置
    private setupMenu(): void {
        this.loading = true;
        this.leftMeneData.map((item, index) => {
            console.log(index, 'index');
            item.sort = index + 1;
        });

        this.rightMeneData.map((item, index) => {
            console.log(index, 'index');
            item.sort = index + 1;
        });
        let datar = this.leftMeneData.concat(this.rightMeneData).concat(this.rightMenuDataAll);
        this.rightMenuDataAll = uniqueFunc(datar, 'resourceCode');
        let datas = this.rightMenuDataAll;
        console.log(datas, 'datas');
        this.$axios
            .post('/userManage/update/resource/sort', datas)
            .then(res => {
                this.loading = false;
                this.yh_message_success('编辑成功');
                this.dialogMenu = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 左侧菜单拖动不生效 key改变重新渲染
    draggableChange() {
        this.draggableKeyLeft++;
    }
    // 获取左边菜单key
    private getMenuKey(key: string): void {
        let curRightData = this.rightMeneData.map((item, index) => {
            console.log(index, 'index');
            item.sort = index + 1;
            return item;
        });
        let datas = this.tableDataInfo
            .filter((item: any) => item.sourceType === '1' && item.resourceParentCode === key)
            .sort((a: any, b: any) => a.sort - b.sort);
        this.rightMeneData = datas;
        let datar = this.rightMenuDataAll.concat(curRightData);
        this.rightMenuDataAll = uniqueFunc(datar, 'resourceCode');
        console.log(this.rightMeneData, 'rightMeneData');
    }

    // 分页
    private handleCurrentChange(): void {
        this.tableData = getCurrentPageData(this.sumUserInfo, this.pages.currentPage, this.pages.pageSize);
        this.key++;
    }

    // 新增
    handleBtnAdd() {
        this.menuInfo = JSON.parse(JSON.stringify(this.menuInfoModule));
        this.dialogAU = true;
        this.dialogAUTitle = '新增资源详情';
        this.dialogAUType = 'add';
    }

    // 单条编辑数据
    private lookeMuenInfo(row: any): void {
        console.log(row);

        this.menuInfo = {
            createDate: row.createDate,
            createTime: row.createTime,
            key: row.key,
            menuIcon: row.menuIcon,
            menuUrl: row.menuUrl ?? '',
            parentValid: row.parentValid,
            resourceCode: row.resourceCode,
            resourceName: row.resourceName,
            resourceParentCode: row.resourceParentCode,
            show: !!row.show,
            sort: row.sort,
            sourceType: row.sourceType,
        };
        console.log(this.menuInfo, 'menuInfo--------------');

        this.dialogAU = true;
        this.dialogAUTitle = '修改资源详情';
        this.dialogAUType = 'update';
        this.$nextTick(() => {
            let node = (this.$refs['tree-select'] as any).getNode(row.resourceCode);
            this.menuInfo['level'] = node.level - 1 || 0;
            console.log(this.menuInfo['level'], '------------------');
        });
    }

    // 编辑
    private menuInfoConfirm(): void {
        let url = '';
        let title = '';
        if (this.menuInfo['level'] == 2 && this.menuInfo.sourceType == '1' && !this.menuInfo.menuUrl) {
            // 层级为2且为菜单的话需要添加菜单路径
            this.yh_message_warn('菜单路径不可为空!');
            return;
        }
        if (this.dialogAUType == 'add') {
            url = '/userManage/add/resource';
            title = '新增成功';
        } else if (this.dialogAUType == 'update') {
            url = '/userManage/update/resource';
            title = '编辑成功';
        }
        this.loading = true;
        this.$axios
            .post(url, this.menuInfo)
            .then(res => {
                this.yh_message_success(title);
                this.getUserResource(true);
                this.dialogAU = false;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 导出
    loadout() {
        downLoadFile({
            method: 'post',
            url: '/export/table/data',
            data: { codes: [], table: 'TB_RESOURCE', deleteRecord: false, dimensionField: '', querySql: '' },
            loading: true,
            loadingMsg: '正在准备导出，请稍后··· ···',
        });
    }

    // 重置
    private resetInfo(): void {
        this.selectInfo = {
            resourceCode: '',
            resourceName: '',
            resourceParentCode: '',
            sourceType: '',
            show: null,
        };
    }
}
</script>
<style lang="scss" scoped>
.user-resource {
    .resource-list {
        & /deep/ .el-button--mini {
            padding: 2px 8px !important;
        }
    }

    .user-hared {
        border: 1px solid #eee;
        padding: 8px;
    }

    .dialog-p-input {
        width: 220px;
    }

    .user-resource-div {
        position: relative;

        .user-resource-div-lift,
        .user-resource-div-right {
            width: 217px;

            .user-resource-text-conter {
                width: 217px;
                height: 317px;
                white-space: nowrap;
                overflow-y: auto;
                overflow-x: auto;
                border: 1px solid #eee;

                p {
                    width: 100%;
                    margin-bottom: 10px;
                    cursor: pointer;
                    padding: 8px;

                    // &:hover {
                    //     cursor: move;
                    // }
                }
            }
        }

        .user-resource-div-right {
            position: absolute;
            right: 0px;
            top: 0px;
        }
    }
}
.chosen {
    background-color: #40a9ff;
}
/deep/ .el-form-item--mini.el-form-item {
    margin-bottom: 22px;
}
/deep/ .el-dialog .el-dialog__body {
    padding: 40px 30px !important;
}
</style>
